package com.wenyu.wenyuyuedu.activity.homepage;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.mcxtzhang.swipemenulib.SwipeMenuLayout;
import com.wenyu.wenyuyuedu.R;
import com.wenyu.wenyuyuedu.activity.LoginActivity;
import com.wenyu.wenyuyuedu.bean.homepager.DeleteMenberMangeBean;
import com.wenyu.wenyuyuedu.bean.homepager.MemberManageBean;
import com.wenyu.wenyuyuedu.global.ApiWrapper;
import com.wenyu.wenyuyuedu.global.QBangApis;
import com.wenyu.wenyuyuedu.index.MenberIndexAdapter;
import com.wenyu.wenyuyuedu.index.PinyinComparator;
import com.wenyu.wenyuyuedu.index.PinyinUtils;
import com.wenyu.wenyuyuedu.index.SlideBar;
import com.wenyu.wenyuyuedu.index.User;
import com.wenyu.wenyuyuedu.server.homepager.DeleteMenberMangeServer;
import com.wenyu.wenyuyuedu.server.homepager.MemberManageServer;
import com.wenyu.wenyuyuedu.utils.AbSharedUtil;
import com.wenyu.wenyuyuedu.utils.MyToast;
import com.wenyu.wenyuyuedu.utils.SharedConstants;
import com.wenyu.wenyuyuedu.utils.StatusBarUtil;

import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/*
* 成员管理
* */
public class MenberMangeMentActivity extends AppCompatActivity implements SlideBar.onLetterTouchedChangeListener, View.OnClickListener {

    @InjectView(R.id.member_left)
    ImageView memberLeft;
    @InjectView(R.id.circle_et_sousuo)
    EditText circleEtSousuo;
    @InjectView(R.id.lv)
    ListView lv;
    @InjectView(R.id.slideBar)
    SlideBar slideBar;
    @InjectView(R.id.tv_show)
    TextView tvShow;
    private MenberIndexAdapter menberIndexAdapter;
    private List<User> list;
    private Activity activity;
    private List<MemberManageBean.InfoBean> infoList = new ArrayList<>();
    private List<MemberManageBean.InfoBean> info;
    private String object_id;
    private String uid;
    private String token;
    private String helpfeed_user_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menber_mange_ment);
        ButterKnife.inject(this);
        this.activity = MenberMangeMentActivity.this;
        StatusBarUtil.setStatusBar(MenberMangeMentActivity.this, R.color.white);
        initView();
        list = new ArrayList<>();
        slideBar.setTextViewDialog(tvShow);
        slideBar.setOnLetterTouchedChangeListener(this);
        menberIndexAdapter = new MenberIndexAdapter(MenberMangeMentActivity.this, helpfeed_user_id);
        lv.setAdapter(menberIndexAdapter);
        menberIndexAdapter.setItemOnClickListener(new MenberIndexAdapter.itemOnClickListener() {
            @Override
            public void onClick(int position, View v) {
                switch (v.getId()) {
                    case R.id.tv:
                        break;
                    case R.id.btn_delete:
                        SwipeMenuLayout layout = (SwipeMenuLayout) v.getParent();
                        layout.quickClose();
                        String uid = list.get(position).getUid();
                        if (helpfeed_user_id.equals(uid)) {
                            MyToast.showToast(MenberMangeMentActivity.this, "不能删除圈主", Toast.LENGTH_SHORT);
                            return;
                        } else {
                            String user_id = list.get(position).getUid();
                            deleteMenberMangeMent(position, user_id);
                        }
                        break;
                }

            }
        });
        requestData();
    }

    /*删除成员*/
    private void deleteMenberMangeMent(final int position, String user_id) {
        DeleteMenberMangeServer deleteMenberMangeServer = ApiWrapper.getInstance().create(DeleteMenberMangeServer.class);
        Call<DeleteMenberMangeBean> dalete = deleteMenberMangeServer.getDalete(token, object_id, user_id);
        dalete.enqueue(new Callback<DeleteMenberMangeBean>() {
            @Override
            public void onResponse(Call<DeleteMenberMangeBean> call, Response<DeleteMenberMangeBean> response) {
                DeleteMenberMangeBean body = response.body();
                if (body != null) {
                    int code = body.getCode();
                    if (code == 1) {
                        MyToast.showToast(activity, "删除成功", Toast.LENGTH_SHORT);
                        menberIndexAdapter.getmList().remove(position);
                        list.remove(position);
                        menberIndexAdapter.notifyDataSetChanged();
                    } else if (code == 3802) {
                        MyToast.showToast(activity, "你不是圈主，无权删除", Toast.LENGTH_SHORT);
                    } else if (code == 3803) {
                        MyToast.showToast(activity, "系统延迟，请您稍后重试！", Toast.LENGTH_SHORT);
                    } else if (code == 3804) {
                        MyToast.showToast(activity, "已经移出成功，您可以刷新页面后看到", Toast.LENGTH_SHORT);
                    }
                } else {
                    MyToast.showToast(activity, "网络异常", Toast.LENGTH_SHORT);
                }
            }

            @Override
            public void onFailure(Call<DeleteMenberMangeBean> call, Throwable t) {
                MyToast.showToast(activity, "网络异常", Toast.LENGTH_SHORT);
            }
        });
    }

    private void initView() {
        Intent intentGet = getIntent();
        /*圈子的id*/
        object_id = intentGet.getStringExtra("object_id");
        /*发帖人的uid*/
        uid = intentGet.getStringExtra("myattention");
        helpfeed_user_id = intentGet.getStringExtra("helpfeed_user_id");
        memberLeft.setOnClickListener(this);
        token = AbSharedUtil.getString(MenberMangeMentActivity.this, SharedConstants.USER_TOKEN);
    }

    private static final int SHOW_NICKNAME = 0;

    /*获取网络据*/
    private void requestData() {
        String token = AbSharedUtil.getString(activity, SharedConstants.USER_TOKEN);
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(QBangApis.BaseAPI + "/forum/circle/circleManageShow.html/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        MemberManageServer memberManageServer1 = retrofit.create(MemberManageServer.class);
        Call<MemberManageBean> memberManage1 = memberManageServer1.getMemberManage(token, object_id);
        memberManage1.enqueue(new Callback<MemberManageBean>() {
            @Override
            public void onResponse(Call<MemberManageBean> call, Response<MemberManageBean> response) {
                MemberManageBean body = response.body();
                if (body != null) {
                    int code = body.getCode();
                    //  initDAta();
                    if (code == 1) {
                        info = body.getInfo();
                        if (info.size() == 0) {
                            MyToast.showToast(activity, "暂无成员", Toast.LENGTH_SHORT);
                        } else {
                            initDAta();
                            menberIndexAdapter.addAll(list);
                            menberIndexAdapter.setListAll(info);
                        }
                    } else if (code == 0) {
                        showLoginDoalog();
                    } else if (code == 3700) {
                        MyToast.showToast(activity, "需要您登陆之后才可以查看的哦", Toast.LENGTH_SHORT);
                    } else if (code == 3701) {
                        MyToast.showToast(activity, "圈子不存在或者已经被冻结！", Toast.LENGTH_SHORT);
                    }
                }
            }

            @Override
            public void onFailure(Call<MemberManageBean> call, Throwable t) {
                MyToast.showToast(activity, "暂无成员", Toast.LENGTH_SHORT);
            }
        });
    }

    private void initDAta() {
        //   String[] contactArray = getResources().getStringArray(R.array.contacts);
        List<User> contacts = new ArrayList<User>(info.size());
        for (int i = 0; i < info.size(); i++) {
            try {
                User contact = new User();

                contact.setName(info.get(i).getNickname());
                contact.setPath(info.get(i).getPath());
                contact.setUid(info.get(i).getUid());
                String firstLetter = PinyinUtils.getPinyinOfHanyu(info.get(i).getNickname()).substring(0, 1).toUpperCase();
                if (firstLetter.matches("[A-Z]")) {
                    contact.setFirstLetter(firstLetter);
                } else {
                    contact.setFirstLetter("#");
                }
                contacts.add(contact);
            } catch (BadHanyuPinyinOutputFormatCombination e) {
                e.printStackTrace();
            }
        }
        Collections.sort(contacts, new PinyinComparator());
        list.addAll(contacts);
    }


    @Override
    public void onTouchedLetterChange(String letterTouched) {
        int position = menberIndexAdapter.getPositionForSection(letterTouched.charAt(0));
        if (position != -1) {
            lv.setSelection(position);
        }
    }

    android.app.AlertDialog ad;
    private TextView quxiao;
    private TextView queding;

    /*显示登陆的dialog*/
    private void showLoginDoalog() {

        ad = new android.app.AlertDialog.Builder(activity).create();
        ad.show();
        Window window = ad.getWindow();
        window.setContentView(R.layout.dailog_login);
        quxiao = (TextView) window.findViewById(R.id.dialog_login_quxiao);
        queding = (TextView) window.findViewById(R.id.dialog_login_queding);
        quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ad.dismiss();
            }
        });
        queding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AbSharedUtil.putString(MenberMangeMentActivity.this, SharedConstants.USER_TOKEN, "");
                Intent intent = new Intent();
                intent.setClass(activity, LoginActivity.class);
                startActivity(intent);
                finish();
                ad.dismiss();
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.member_left:
                finish();
                break;
        }
    }
}
